#include "tcpclient.h"
#include <QJsonDocument>
#include <QDataStream>
#include <QDebug>

TcpClient::TcpClient(QObject *parent)
    : QObject(parent),
    m_packetSize(0) // 初始化包大小为0
{
    m_socket = new QTcpSocket(this);

    // 连接QTcpSocket的内置信号到我们自己的槽函数
    connect(m_socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
    connect(m_socket, &QTcpSocket::errorOccurred, this, &TcpClient::onErrorOccurred);
}

TcpClient::~TcpClient()
{
    // 析构函数通常为空，因为m_socket的父对象是this，会被自动销毁
}

void TcpClient::connectToServer(const QString &host, quint16 port)
{
    if (m_socket->state() == QAbstractSocket::UnconnectedState) {
        qDebug() << "[Client] Attempting to connect to" << host << ":" << port;
        m_socket->connectToHost(host, port);
    }
}

void TcpClient::sendJson(const QJsonObject &jsonObj)
{
    if (m_socket->state() != QAbstractSocket::ConnectedState) {
        qWarning() << "[Client] Not connected to server. Cannot send message.";
        return;
    }

    // 1. 将 JSON 对象转换为 QByteArray
    QByteArray jsonData = QJsonDocument(jsonObj).toJson(QJsonDocument::Compact);

    // 2. 按照我们的协议封包：[长度-内容]
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_6_0);
    out << (qint32)jsonData.size();
    out.writeRawData(jsonData.constData(), jsonData.size());

    // 3. 发送数据
    m_socket->write(block);
    m_socket->flush();

    qDebug() << "[Client] Sent JSON:" << jsonObj;
}

void TcpClient::disconnectFromServer()
{
    m_socket->disconnectFromHost();
}

void TcpClient::onReadyRead()
{
    // --- 这里是完整的、健壮的拆包逻辑 ---
    m_buffer.append(m_socket->readAll());

    while (true) {
        if (m_packetSize == 0) {
            if (m_buffer.size() < sizeof(qint32)) {
                break;
            }
            QDataStream stream(m_buffer);
            stream.setVersion(QDataStream::Qt_6_0);
            stream >> m_packetSize;
            m_buffer.remove(0, sizeof(qint32));
        }

        if (m_packetSize > 0) {
            if (m_buffer.size() < m_packetSize) {
                break;
            }

            QByteArray packetData = m_buffer.left(m_packetSize);
            m_buffer.remove(0, m_packetSize);

            // 成功解析出一个完整的JSON包，发射信号
            QJsonDocument doc = QJsonDocument::fromJson(packetData);
            if (!doc.isNull() && doc.isObject()) {
                qDebug() << "[Client] Received JSON:" << doc.object();
                emit serverResponse(doc.object());
            }

            m_packetSize = 0; // 重置，准备接收下一个包
        }
    }
}

void TcpClient::onConnected()
{
    qDebug() << "[Client] Connected to server!";
    emit myConnectedToServer();
}

void TcpClient::onDisconnected()
{
    qDebug() << "[Client] Disconnected from server.";
    emit myDisconnectedFromServer();
}

void TcpClient::onErrorOccurred(QAbstractSocket::SocketError socketError)
{
    // socketError 参数在 Qt 6 中可能未使用，但函数签名需要它
    Q_UNUSED(socketError);
    qWarning() << "[Client] Socket Error:" << m_socket->errorString();
    emit myConnectErrorOccurred(m_socket->errorString());
}
